package com.bianmaba.spring.security.database.core;

import com.bianmaba.spring.security.basic.BasicSecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DefaultUserDetailsService implements UserDetailsService {
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultResourceDetailsService.class);

    @Autowired
    private BasicSecurityProperties securityProperties;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        LOGGER.warn("没有找到自定义“IResourceDetailsService”实现类，无法读取数据库中的用户信息，将使用配置文件中的用户信息。");
        UserDetails userDetails = null;
        List<Map<String, String>> users = securityProperties.getBasic().getUsers();
        if (!users.isEmpty()) {
            for (Map<String, String> user : users) {
                if (user.get("username").equals(username)) {
                    String[] roles = user.get("roles").split("[,]");
                    List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>(0);
                    for (String role : roles) {
                        authorities.add(new SimpleGrantedAuthority(role));
                    }
                    String password = user.get("password");
                    password = new Md5PasswordEncoder().encodePassword(password, null);
                    userDetails = new LocalUserDetails(username, password, authorities);
                }
            }
        } else {
            LOGGER.error("没有找到配置文件中（security.basic.users）的用户信息。");
        }
        if (userDetails == null) {
            throw new UsernameNotFoundException("Username not found!");
        } else {
            return userDetails;
        }
    }
}
